package main

import (
	"flag"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var engine *xorm.Engine
var err error

var (
	packageName string
	genJson     bool
	genDB       bool
	host        string
	structPre   string
)

func main() {
	flag.StringVar(&packageName, "p", "", "package name")
	flag.BoolVar(&genJson, "j", false, "gen json column")
	flag.BoolVar(&genDB, "d", false, "gen db column")
	flag.StringVar(&host, "h", "", "mysql host")
	flag.StringVar(&structPre, "pre", "", "struct prefix")

	flag.Parse()

	if packageName == "" {
		panic("please set package name")
	}

	engine, err = xorm.NewEngine("mysql", host)
	if err != nil {
		panic(err.Error())
	}

	tables, err := engine.DBMetas()
	if err != nil {
		panic(err.Error())
	}

	for _, table := range tables {
		tableInfo := new(TableInfo)
		tableInfo.FileName = table.Name
		tableInfo.PackageName = packageName
		tableInfo.StructName = genTableName(structPre, table.Name)
		tableInfo.Imports = make([]string, 0)

		tableInfo.ColumnInfos = make([]*ColumnInfo, 0)

		for _, c := range table.Columns() {
			columnInfo := new(ColumnInfo)
			columnInfo.Type = get(c.SQLType.Name)

			if columnInfo.Type == "time.Time" && !alreadyImports("time", tableInfo.Imports) {
				tableInfo.Imports = append(tableInfo.Imports, "time")
			}

			columnInfo.ColName = genColumnStructName(c.Name)
			columnInfo.JsonCol = genColumnJsonName(c.Name)
			columnInfo.DBCol = c.Name
			columnInfo.GenDB = genDB
			columnInfo.GenJson = genJson

			tableInfo.ColumnInfos = append(tableInfo.ColumnInfos, columnInfo)
		}

		parse(tableInfo)
	}

	fmt.Println("over....")
}
